package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    /**
     * 新增用户详情表
     *
     * @param userInfo
     */
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    /**
     * 根据id获取用户信息
     *
     * @param userID
     */
    public UserInfoVo findById(Long userID) {
        UserInfo userInfo = userInfoApi.findById(userID);
        UserInfoVo userInfoVo = new UserInfoVo();
        //拷贝数据到VO对象中
        BeanUtils.copyProperties(userInfo, userInfoVo);

        userInfoVo.setAge(userInfo.getAge().toString());

        return userInfoVo;
    }

    /**
     * 根据id修改用户详情信息
     *
     * @param userInfo
     */
    public void updateById(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    /**
     * 上传头像,补充头像
     *
     * @param filename
     * @param inputStream
     */
    public void deleteHeadPhoto(String filename, InputStream inputStream) {
        //1.先上传头像到第三方,获取url路径
        String imageUrl = ossTemplate.upload(filename, inputStream);
        //3.进行人脸识别
        Boolean detect = aipFaceTemplate.detect(imageUrl);

        if (!detect) {
            //如果人脸识别失败则删除远程仓库的图片
            ossTemplate.deleteImage(imageUrl);
            throw new BusinessException(ErrorResult.faceError());
        }else {
            //人脸识别成功,存入用户详情表中
            Long userId = UserHolder.getUserId();
            UserInfo userInfo = new UserInfo();
            userInfo.setId(userId);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }

    /**
     * 修改头像
     * @param headPhoto
     */
    public void updateHeader(MultipartFile headPhoto) throws IOException {
        //保存头像到OSS中,获取url路径
        String url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //调用API修改头像
        userInfoApi.updateHeader(url,UserHolder.getUserId());
    }
}
